//
//  FANKeyboardView.swift
//  Weibo - Swift
//
//  Created by user on 16/4/26.
//  Copyright © 2016年 user. All rights reserved.
//

import UIKit

class FANKeyboardView: UIView {
    
    lazy var toolView:FANKeyboardTools = {
    
        let toolView = FANKeyboardTools(frame: CGRectZero)
        
        toolView.didToolsClickClosure = { [weak self] (type)->() in
        
            let indexPath = NSIndexPath(forItem: 0, inSection: type.rawValue)
        
            self!.emoticonCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
            
            self!.showPageControl(indexPath)
            
        }
        
        return toolView
    }()
    
    lazy var emoticonCollectionView:UICollectionView = {
       
        let layout = UICollectionViewFlowLayout()
        
        layout.minimumInteritemSpacing = 0

        layout.minimumLineSpacing = 0
        
        layout.scrollDirection = .Horizontal
        
        let emoticonCollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        
        emoticonCollectionView.pagingEnabled = true
        
        emoticonCollectionView.bounces = false
        
        emoticonCollectionView.dataSource = self
        
        emoticonCollectionView.delegate = self
        
        emoticonCollectionView.showsHorizontalScrollIndicator = false
        
        return emoticonCollectionView
    }()
    
    lazy var emoticonPageControl:UIPageControl = {
    
        let pageControl = UIPageControl()
        
        pageControl.hidden = true
        
        pageControl.userInteractionEnabled = false
        
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        
        return pageControl
    
    }()
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        let layout = emoticonCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = emoticonCollectionView.frame.size
    }

    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI(){
        
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        
        addSubview(toolView)
        
        toolView.snp_makeConstraints { (make) -> Void in
            
            make.bottom.leading.trailing.equalTo(self)

            make.height.equalTo(37)
        }
        
        addSubview(emoticonCollectionView)
        addSubview(emoticonPageControl)

        
        emoticonCollectionView.snp_makeConstraints { (make) -> Void in
            
            make.top.leading.trailing.equalTo(self)
            
            make.bottom.equalTo(toolView.snp_top)
        }
        
        emoticonPageControl.snp_makeConstraints { (make) -> Void in
            
            make.bottom.equalTo(toolView.snp_top)
            
            make.centerX.equalTo(toolView)
        }
        
        emoticonCollectionView.registerClass(FANEmojiCell.self, forCellWithReuseIdentifier: "emojiCell")
        
    }

}

extension FANKeyboardView:UICollectionViewDataSource,UICollectionViewDelegate{
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return FANEmoticonViewModel.sharedEmoticon.allEmoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return FANEmoticonViewModel.sharedEmoticon.allEmoticons[section].count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("emojiCell", forIndexPath: indexPath) as! FANEmojiCell
        
        cell.emoticons = FANEmoticonViewModel.sharedEmoticon.allEmoticons[indexPath.section][indexPath.item]
        
        cell.indexPath = indexPath
        
        return cell
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        var center = scrollView.center
        
        center.x = center.x + scrollView.contentOffset.x
        
        let cells = emoticonCollectionView.visibleCells()
        
        let indexPath:NSIndexPath
        
        if cells.count == 2{
            
            let firstCell = cells.first
            
            let lastCell = cells.last
            
            if CGRectContainsPoint((firstCell?.frame)!, center){
                
                indexPath = emoticonCollectionView.indexPathForCell(firstCell!)!
                
            }else{
                
                indexPath = emoticonCollectionView.indexPathForCell(lastCell!)!
            }
            
        }else{
            
            indexPath = emoticonCollectionView.indexPathForCell(cells.first!)!
            
        }
        
        self.toolView.selectedSection = indexPath.section
        
        self.showPageControl(indexPath)
        
    }
    
    func showPageControl(indexPath:NSIndexPath){
        
        emoticonPageControl.numberOfPages = FANEmoticonViewModel.sharedEmoticon.allEmoticons[indexPath.section].count
        
        emoticonPageControl.currentPage = indexPath.item
        
        emoticonPageControl.hidden = indexPath.section == 0
        
    }
    
}

class FANEmojiCell:UICollectionViewCell {
    
    var indexPath:NSIndexPath?{
        
        didSet{
            
            self.delectedButton.hidden = indexPath?.section == 0
            
            self.label.hidden = indexPath?.section != 0
        }
    }
    
    var emoticons:[FANEmoticon]?{
        
        didSet{
            
            guard let e = emoticons else{
                
                return
            }
            
            for value in emoticonButtons {
                
                value.hidden = true
                
            }
            
            
            
            for (index,value) in e.enumerate() {
                
                
                
                emoticonButtons[index].hidden = false
                
                let button = emoticonButtons[index]
                
                button.emoticon = value
            }
                
        }
    }
    
    var emoticonButtons:[FANEmoticonButton] = []
    
    lazy var delectedButton:UIButton = {
    
        let button = UIButton()
        
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted);
        
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal);
        
        button.addTarget(self, action: "didDelectedButton:", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button;
    
    }()
    
    lazy var popView:FANPopView = {
        
        let popView = FANPopView.popView()
        
        return popView
    }()
    
    lazy var label:UILabel = {
    
        let label = UILabel()
        
        label.text = "最近使用表情"
        
        label.textColor = UIColor.grayColor()
        
        label.font = UIFont.systemFontOfSize(13)
        
        return label
    
    }()
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func didDelectedButton(button:UIButton){
        
        NSNotificationCenter.defaultCenter().postNotificationName("FANDidDelectedNSNotification", object: nil)
    }
    
    func setupUI(){
        
        backgroundColor = UIColor.whiteColor()
        
        addEmoticonButton()
        
        contentView.addSubview(self.delectedButton)
        
        contentView.addSubview(self.label)
        
        let longPress = UILongPressGestureRecognizer(target: self, action: "longPress:")
        
        contentView.addGestureRecognizer(longPress)
    }
    
    func addEmoticonButton(){
        
        for _ in 0..<Int(FANEmoticonCount){
            
            let button = FANEmoticonButton()
            
            button.hidden = true
            
            button.addTarget(self, action: "didEmoticonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            contentView.addSubview(button)
            
            emoticonButtons.append(button)
        }
        
    }
    
    func longPress(ges:UILongPressGestureRecognizer){
        
        let loc = ges.locationInView(ges.view)
        
        func buttonWithLocation(location:CGPoint) -> FANEmoticonButton?{
            
            for value in emoticonButtons{
                
                if  CGRectContainsPoint(value.frame, location){
                    
                    return value
                }
                
            }
            return nil
        }
        
        guard let button = buttonWithLocation(loc) else{
            
            popView.removeFromSuperview()
            
            return
        }
        
        switch ges.state {
            
            case .Began,.Changed:
                
                if  popView.emojiButton.emoticon == button.emoticon {
                    
                    return
                }
                
                let window = UIApplication.sharedApplication().windows.last!
                
                let rect = button.superview!.convertRect(button.frame, toView: window)
                
                popView.center.x = CGRectGetMidX(rect)
                
                popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
                
                popView.emojiButton.emoticon = button.emoticon
                
                window.addSubview(popView)
                
                break
            
            default:
                
                popView.emojiButton.emoticon = nil
            
                popView.removeFromSuperview()

        }
    
    
    }
    
    func didEmoticonClick(button:FANEmoticonButton){
        
    NSNotificationCenter.defaultCenter().postNotificationName("FANEmoticonButtonClickNotification", object: nil, userInfo: ["emoticon":button.emoticon!])
        
//        print(button.emoticon?.chs)
        
        FANEmoticonViewModel.sharedEmoticon.saveRecentEmoticon(button.emoticon!)
        
        let window = UIApplication.sharedApplication().windows.last!
        
        let popView = FANPopView.popView()
        
        let rect = button.superview!.convertRect(button.frame, toView: window)
        
        popView.center.x = CGRectGetMidX(rect)
        
        popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
        
        popView.emojiButton.emoticon = button.emoticon
        
        window.addSubview(popView)
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.25 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            
            popView.removeFromSuperview()
        }
        
    }
    
    
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        let buttonW = self.contentView.frame.size.width/FANEmoticonCol
        
        let buttonH = (self.contentView.frame.size.height - 25)/FANEmoticonRow
        
        for (index,value) in emoticonButtons.enumerate() {
            
            let col = index % Int(FANEmoticonCol)
            
            let row = index / Int(FANEmoticonCol)
            
            let emoticonButtonX = CGFloat(col) * buttonW
            
            let emoticonButtonY = CGFloat(row) * buttonH
            
            value.frame = CGRectMake(emoticonButtonX, emoticonButtonY, buttonW, buttonH)
        }
     
        
        let x = contentView.frame.width - buttonW
        
        let y = contentView.frame.height - buttonH
        
        self.delectedButton.frame = CGRectMake(x, y - 25, buttonW, buttonH)
     
        self.label.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(contentView.snp_bottom).offset(-20)
            
            make.centerX.equalTo(contentView.snp_centerX)
        }
        
    }
    
    

    
}
